package com.hxzy.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.hxzy.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * fastdfs实现文件上传
 */

@Service
public class FastDfsFileUploadServiceImpl implements FileUploadService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;


    /**
     * fastfds的主机地址和端口
     */
    @Value(value = "${fdfs.domain}")
    private String doMain;


    @Override
    public String uploadImage(MultipartFile file) throws IOException {

        //原始名称
        String originalFilename = file.getOriginalFilename();
        //得到扩展名
        String fileExtName= originalFilename.substring( originalFilename.lastIndexOf(".")+1);

        Set<MetaData> metaDataSet=new HashSet<>();
        metaDataSet.add(new MetaData("name", originalFilename));
        metaDataSet.add(new MetaData("size", file.getSize()+""));

        StorePath storePath = this.fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), fileExtName, metaDataSet);

        return doMain+storePath.getFullPath();
    }

    @Override
    public String uploadImageAndCrtThumbImage(MultipartFile file) throws IOException {
        //原始名称
        String originalFilename = file.getOriginalFilename();
        //得到扩展名
        String fileExtName= originalFilename.substring( originalFilename.lastIndexOf(".")+1);

        Set<MetaData> metaDataSet=new HashSet<>();
        metaDataSet.add(new MetaData("name", originalFilename));
        metaDataSet.add(new MetaData("size", file.getSize()+""));

        StorePath storePath = this.fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), fileExtName, metaDataSet);

        return doMain+storePath.getFullPath();
    }
}
